<?php
/**
 * This file contains all functionality necessary for adding a custom `Portfolio Widget`
 * 
 * @author Mike Burns
 * @uses WP_Widget
 */

// WordPress hooks

/**
 * WordPress hook for registering custom widgetsa
 */
function cdia_port_register_portfolio_widget() {

	// Register new widget using the name of the WP_Widget subclass
	register_widget( 'cdia_portfolio_widget' );

}

/**
 * Custom WP_Widget subclass for Portfolio Widget
 * 
 * @uses WP_Widget
 */
class cdia_portfolio_widget extends WP_Widget {

	/**
	 * Constructor for cdia_portfolio_widget class
	 * 
	 * Called automatically when a cdia_portfolio_widget object is created
	 * 	- i.e. $my_widget = new cdia_portfolio_widget();
	 * 
	 * This happens when the widget is registered using register_widget
	 */
	function cdia_portfolio_widget() {

		// Set up custom widget options
		$widget_ops = array(
		    'classname' => 'cdia_portfolio_widget',
		    'description' => 'Display a thumbnail and title for your latest portfolio items.'
		);

		// Call the parent constructor to handle the heavy lifting
		$this->WP_Widget( 'cdia_portfolio_widget', 'Portfolio Widget', $widget_ops );
	}

	/**
	 * This method renders the admin form for the Portfolio Widget
	 * 
	 * @param Array $instance The widget instance this form belongs to 
	 */
	function form( $instance ) {
	
		// Setup default widget arguments
		$default_args = array(
		    'title' => '',
		    'count' => 3,
		    'show_thumb' => true,
		    'show_description' => false
		);
		
		// Merge with existing values
		$instance = wp_parse_args( $instance, $default_args );

		// Convert $instance Array -> PHP variables
		extract( $instance ); 
		
		// BEGIN HTML OUTPUT (Would be cleaner to contain in separate file, included here for brevity...) ?>
		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
			<input id="<?php echo $this->get_field_id( 'title' ); ?>" class="widefat" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'count' ); ?>">Number of Items to Show:</label>
			<input id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" type="text" value="<?php echo esc_attr( $count ); ?>" size="3" />
		</p>
		<p>
			<input id="<?php echo $this->get_field_id( 'show_thumb' ); ?>" class="checkbox" name="<?php echo $this->get_field_name( 'show_thumb' ); ?>" type="checkbox" value="1" <?php checked( $show_thumb ); ?> />
			<label for="<?php echo $this->get_field_id( 'show_thumb' ); ?>" >Show Thumbnail?</label>
		</p>
		<p>
			<input id="<?php echo $this->get_field_id( 'show_description' ); ?>" class="checkbox" name="<?php echo $this->get_field_name( 'show_description' ); ?>" type="checkbox" value="1" <?php checked( $show_description ); ?> />
			<label for="<?php echo $this->get_field_id( 'show_description' ); ?>">Show Description?</label>
		</p>
		<?php // END HTML OUTPUT
	}

	/**
	 * Widget admin update callback
	 * 
	 * Runs when the 'Update' button is hit in an instance of our Portfolio Widget
	 * 
	 * @param Array $new_instance Array containing new input values
	 * @param Array $old_instance Array containing old input values
	 * 
	 * @return Array Input values to be stored for this widget instance
	 */
	function update( $new_instance, $old_instance ) {
		
		// Start from old widget values
		$instance = $old_instance;

		// Sanitize and update to new widget values
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['count'] = absint( $new_instance['count'] );
		$instance['show_thumb'] = absint( $new_instance['show_thumb'] );
		$instance['show_description'] = absint( $new_instance['show_description'] );
		
		// Return clean and updated widget values
		return $instance;
		
	}

	/**
	 * Front-end widget display callback
	 * 
	 * Runs when a page with a dynamic sidebar containg a Portfolio Widget instance is displayed
	 * 
	 * @global stdObject $post The current post being displayed
	 * @param Array $args Assorted widget arguments
	 * @param Array $instance The current instance values
	 */	
	function widget( $args, $instance ) {
		global $post;

		// Setup query arguments for get_posts
		$query_args = array(
		    'numberposts' => $instance['count'],
		    'post_type' => 'portfolio',
		    'post_status' => 'publish'
		);

		// Fetch portfolio posts
		$portfolio_items = get_posts( $query_args );

		// Don't display the widget if we don't have any portfolio items to display
		if( !empty( $portfolio_items ) ) {

			// This widget title
			$portfolio_widget_title = $instance['title'];
			
			// Display portfolio listing as an unordered list
			$portfolio_widget_content = '<ul class="portfolio-listing">';
		
			// Loop through each portfolio item
			foreach( $portfolio_items as $post ) {
				
				// Setup post variables for current portfolio post
				// @note This allows us to use loop template tags (the_content, the_title, etc.) now
				setup_postdata( $post );

				// Each portfolio item is a list item
				$portfolio_widget_content .= '<li>';
				
				// Print the heading with a link to the portfolio post
				$portfolio_widget_content .= sprintf( '<a href="%s">%s</a>', get_permalink(), get_the_title() );
				
				// Show thumbnail if the widget settings ask for it
				if( $instance['show_thumb'] ) {

					// Get thumbnail sized version of this posts' featured image
					$thumb = get_the_post_thumbnail( get_the_ID(), 'thumbnail' );

					// Wrap thumbnail img with permalink
					$portfolio_widget_content .= sprintf( '<a href="%s">%s</a>', get_permalink(), $thumb );
				}
				
				// Show description (post content) if the widget settings ask for it
				if( $instance['show_description'] ) {
					
					$portfolio_widget_content .= sprintf( '<p>%s</p>', get_the_content() );
				}
			
				// Close out this portfolio item list item
				$portfolio_widget_content .= '</li>';
			}
			
			// Close out portfolio listing unordered list
			$portfolio_widget_content .= '</ul>';
		
			// Display widget content
			echo $args['before_widget'] . 
			     $args['before_title'] . $portfolio_widget_title . $args['after_title'] .
			     $portfolio_widget_content .
			     $args['after_widget'];
				
		}
		
		// ALWAY reset postdata after get_posts
		wp_reset_postdata();

	}
}

?>